package com.javakc.copyrightin.chapter.controller;

import com.javakc.commonutils.api.APICODE;
import com.javakc.copyrightin.chapter.entity.Chapter;
import com.javakc.copyrightin.chapter.service.ChapterService;
import com.javakc.copyrightin.chapter.vo.ChapterQuery;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "章节信息管理")
@RestController
@RequestMapping("/copyrightin/chapter")
@CrossOrigin
public class ChapterController {

    @Autowired
    private ChapterService chapterService;


    @ApiOperation("带分页的条件查询")
    @PostMapping("{pageNo}/{pageSize}")
    public APICODE findPage(
            @ApiParam(name="pageNo",value = "当前页码",required = true) @PathVariable("pageNo") int pageNo,
            @ApiParam(name="pageSize",value = "每页显示的最大条数",required = true) @PathVariable("pageSize") int pageSize,
            @ApiParam(name="bookQuery",value = "查询条件封装对象",required = false) @RequestBody(required = false) ChapterQuery chapterQuery){
        Page<Chapter> page = chapterService.findPage(pageNo, pageSize, chapterQuery);
        List<Chapter> list = page.getContent();
        long totalElements = page.getTotalElements();
        return APICODE.OK().data("items",list).data("total",totalElements);
    }

    @ApiOperation(value = "修改章节")
    @PutMapping("updateChapter")
    public APICODE updateChapter(@RequestBody Chapter chapter){
        chapterService.saveOrUpdate(chapter);
        return APICODE.OK().data("chapter",chapter);
    }

    @ApiOperation(value = "根据ID获取书籍")
    @GetMapping("{chapterId}")
    public APICODE view(@PathVariable("chapterId") int chapterId){
        Chapter chapter = chapterService.getById(chapterId);
        return APICODE.OK().data("chapter",chapter);
    }

    @ApiOperation(value = "根据ID删除书籍")
    @DeleteMapping("{id}")
    public APICODE deleteChapter(@PathVariable int id){
        chapterService.removeById(id);
        return APICODE.OK();
    }

    @ApiOperation(value = "书籍上下架")
    @PutMapping("upOrDownChapter/{id}/{status}")
    public APICODE upOrDownChapter(@PathVariable Integer id, @PathVariable Integer status){
        Chapter chapter=chapterService.getById(id);
        chapter.setStatus(status);
        chapterService.saveOrUpdate(chapter);


        // 添加到正式章节表
        chapterService.insert(id);
        return APICODE.OK();
    }

}
